import { getOrderByNoRemind } from "@/api/hotel/order";
import { getToken } from '@/utils/auth'
import { Notification } from 'element-ui'
import router from '@/router';
import { Howl } from 'howler';

const handleNotificationClick = () => {
    router.push({ path: '/hotel/order' });
};

function initAudio(src) {
    const sound = new Howl({
        src: [src], // 音频文件路径
        html5: true, // 强制使用 HTML5 Audio 而不是 Web Audio API（可选）
        format: ['mp3'],
        onplay: () => {
            console.log('音频开始播放');
        },
        onload: () => {
            console.log('音频加载完毕');
        },
        onend: () => {
            console.log('音频播放结束');
        },
        onpause: () => {
            console.log('音频暂停');
        },
        onloaderror: (id, error) => {
            console.error('音频加载失败:', error);
        }
    });
    return sound;
}

var audio = initAudio(require('@/assets/mp3/order4.mp3'));
var audio1 = initAudio(require('@/assets/mp3/cs1.mp3'));


setInterval(() => {
    if (getToken()) {
        getOrderByNoRemind().then(response => {
            var datas = response.data;

            if (datas.length > 0) {
                audio.play();
                for (var i = 0; i < datas.length; i++) {
                    const hotelName = datas[i].hotelName + '[' + datas[i].bsHotelId + ']';
                    const orderType = datas[i].orderType;
                    setTimeout(function () {
                        if (orderType === 0) {
                            Notification.warning({
                                title: '新订单',
                                message: hotelName,
                                type: 'success',
                                onClick: handleNotificationClick
                            })
                        } else {
                            Notification.warning({
                                title: '取消订单',
                                message: hotelName,
                                type: 'success',
                                onClick: handleNotificationClick
                            })
                        }
                    }, 500);
                }
            }
        }
        );
    }
}, 20000);


/**
 * Webscoket集成
 * ws.readyState
 * 0 - CONNECTING：连接尚未建立。
 * 1 - OPEN：连接已建立，可以进行通信。
 * 2 - CLOSING：连接正在关闭。
 * 3 - CLOSED：连接已经关闭或未能成功打开。
 */
var webscoketUrl = 'ws://47.96.100.131:8083/websocket/';
// var webscoketUrl = 'ws://127.0.0.1:8083/websocket/';
var wsuri = webscoketUrl;
let ws;
function createWebSocketConnection() {
    const token = getToken();
    if (token) {
        wsuri = webscoketUrl;
        wsuri += token;
    } else {
        // 如果已经没有了token,但是连接依旧在线,就断开连接
        if (ws && ws.readyState === WebSocket.OPEN) {
            ws.close();
            console.log("关闭连接成功");
            return;
        } else {
            // 没有token,连接也不在线,阻拦往下执行
            return;
        }
    }

    // 如果已经连接就不在重新连接
    if (ws && ws.readyState === WebSocket.OPEN) {
        console.log("已连接");
        return;
    }

    // 关闭旧连接(如果有的话)
    if (ws) {
        try {
            ws.close();
            ws = null;
            console.log("有旧连接");
        } catch (e) {
            console.error("没有旧连接", e);
        }
    }

    // 创建新的WebSocket连接
    ws = new WebSocket(wsuri);

    // 监听消息接收
    ws.onmessage = function (event) {
        // 处理接收到的消息
        const res = JSON.parse(event.data);
        const hotelName = res.hotelName;
        const bsHotelId = res.bsHotelId;
        const message = res.message;
        const orderType = res.orderType;
        if (orderType === 0) {
            audio.play();
            Notification.warning({
                title: '新订单',
                message: hotelName + '[' + bsHotelId + ']',
                type: 'success',
                onClick: handleNotificationClick
            })
        } else if (orderType === 1) {
            audio.play();
            Notification.warning({
                title: '取消订单',
                message: hotelName + '[' + bsHotelId + ']',
                type: 'success',
                onClick: handleNotificationClick
            })
        } else if (orderType === 2) {
            window.location.reload();
        } else if (orderType === 3) {
            console.log("收到消息:" + hotelName);
        } else if (orderType === 4) {
            audio1.play();
            Notification.warning({
                title: '提示',
                message: message,
                type: 'success',
                onClick: handleNotificationClick
            })
        }
    };

    // 监听连接关闭
    ws.onclose = function (event) {
        console.log("WebSocket closed:", event.code, event.reason);
        // 可能需要在此处处理重连逻辑
    };
}

setInterval(createWebSocketConnection, 1500);


// 根据日期查询是星期几
function getWeekDay(dateString) {
    // 创建一个新的 Date 对象，传入的是标准格式的日期字符串。
    const date = new Date(dateString);

    // 检查提供的日期是否有效。
    if (isNaN(date.getTime())) {
        return 'Invalid Date';
    }

    const weekDays = ['一', '二', '三', '四', '五', '六', '日'];

    // getDay() 返回的是 0（周日） 到 6（周六），所以我们需要调整一下。
    const dayOfWeek = (date.getDay() + 6) % 7 + 1;

    return weekDays[dayOfWeek - 1];
}

// 获取当前时间 - yyyy-mm-dd
function getFormattedDate() {
    const today = new Date();
    const year = today.getFullYear();
    let month = today.getMonth() + 1; // Months are zero-based
    let day = today.getDate();

    // Ensure two digits for month and day
    month = String(month).padStart(2, '0');
    day = String(day).padStart(2, '0');

    return `${year}-${month}-${day}`;
}

function getYesterday() {
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(today.getDate() - 1);

    const year = yesterday.getFullYear();
    const month = String(yesterday.getMonth() + 1).padStart(2, '0');
    const day = String(yesterday.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
}

export { getWeekDay, getFormattedDate, getYesterday }